package com.asia5b.a5mall.order.fragment

import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5bmall.same.dialog.OrderCancelDialog
import com.asia5b.a5mall.middleware.base.SimpleActivity
import com.asia5b.a5mall.middleware.base.SimpleFragment
import com.asia5b.a5mall.middleware.config.Asia5bPayUtils
import com.asia5b.a5mall.middleware.event.*
import com.asia5b.a5mall.middleware.logic.viewmodel.order.OrderListFragmentVM
import com.asia5b.a5mall.middleware.model.base.ResultModel
import com.asia5b.a5mall.middleware.model.bean.MenuBean
import com.asia5b.a5mall.middleware.model.bean.OrderListType
import com.asia5b.a5mall.middleware.model.bean.PostParcelBean
import com.asia5b.a5mall.middleware.model.order.OrderDetailModel
import com.asia5b.a5mall.middleware.model.order.OrderPayModel
import com.asia5b.a5mall.middleware.model.order.TradeType
import com.asia5b.a5mall.middleware.utils.*
import com.asia5b.a5mall.middleware.widget.CancelSureViewModel
import com.asia5b.a5mall.order.R
import com.asia5b.a5mall.order.activity.OrderListActivity
import com.asia5b.a5mall.order.adapter.OrderDetailmAdapter
import com.asia5b.a5mall.order.adapter.OrderListAdapter
import com.asia5b.a5mall.order.databinding.FragmentOrderlistBinding
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.scwang.smartrefresh.layout.api.RefreshLayout
import kotlinx.android.synthetic.main.fragment_orderlist.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Created by zhangyuncai on 2020/1/14.
 * 订单列表
 */
class OrderListFragment : SimpleFragment<OrderListFragmentVM, FragmentOrderlistBinding>() {
    override val viewModelClazz: Class<OrderListFragmentVM>
        get() = OrderListFragmentVM::class.java

    override fun getDataBinding(container: ViewGroup?): FragmentOrderlistBinding {
        return FragmentOrderlistBinding.inflate(layoutInflater, container, false)
    }

    //    private lateinit var dialog: LogisticInformationDF// 查看物流dialog
    val mRecyclerView by lazy { rv_orderlist }
    val mDatas = arrayListOf<OrderDetailModel>()
    lateinit var mAdapter: OrderListAdapter<*>
    val emptyView by lazy { newEmptyView(mActivity) }
    var type = OrderListType.ALL
    val orderListActivity by lazy { mActivity as OrderListActivity }
    //state 状态 1：未使用,2:已使用,3:已过期

    //搜索商品编号
    var goods_name: String? = null

    override fun initView() {
        mSmartRefreshLayout = mDataBinding.autoOrderlist
        arguments?.let {
            type = requireArguments().getSerializable("type") as OrderListType
            if (requireArguments().containsKey("goods_name")) {
                goods_name = requireArguments().getString("goods_name")
            }
        }

        mAdapter = OrderListAdapter.newAdapter(type, mDatas)

        mRecyclerView.run {
            layoutManager = LinearLayoutManager(mActivity)
            adapter = mAdapter
        }

        setBottomView()
    }

    fun setBottomView() {
        ll_orderlist_bottom.visibility = (type == OrderListType.APPLY_PACKAGING).judge(View.VISIBLE, View.GONE)

        iv_orderlist_checkall.isSelected = false
        bt_orderlist_parcel.isEnabled = false
        //申请打包全选
        ll_orderlist_checkall.setOnClickListener {
            val checkAll = !(iv_orderlist_checkall.isSelected)
            iv_orderlist_checkall.isSelected = checkAll
            if (mDatas.size > 0) {
                for (detailModel in mDatas) {
                    if (!detailModel.sent_parcel.isNullOrEmpty()) {
                        for (parcelModel in detailModel.sent_parcel!!) {
                            if (parcelModel.isCanParcel) {
                                parcelModel.checked = checkAll
                            }
                        }
                    }
                }
                mAdapter.notifyDataSetChanged()
            }
            notifyAllChecked()
        }
        //提交申请打包
        bt_orderlist_parcel.setOnClickListener {
            val parcelModelList = arrayListOf<PostParcelBean>()
            for (detailModel in mDatas) {
                val sn = detailModel.sn
                val idList = arrayListOf<Int>()
                detailModel?.sent_parcel?.forEach {
                    if (it.checked) {
                        idList.add(it.id)
                    }
                }
                if (idList.size > 0) {
                    parcelModelList.add(PostParcelBean.newPostParcelModel(sn, idList))
                }
            }
            if (parcelModelList.size > 0) {
                push(ActCons.OrderParcelActivity, {
                    it.withSerializable("datas", parcelModelList)
                })
            } else {
            }
        }
    }

    /**
     * 申请打包全选按钮
     */
    fun notifyAllChecked() {
        var checkedsum = 0
        var sum = 0
        if (!mDatas.isNullOrEmpty()) {
            for (orderDetailModel in mDatas) {
                orderDetailModel?.sent_parcel?.forEach {
                    if (it.checked && it.isCanParcel) {
                        checkedsum += 1
                    }
                    if (it.isCanParcel) {
                        sum += 1
                    }
                }
            }
        }
        iv_orderlist_checkall.isSelected = (sum != 0 && (checkedsum == sum))
        bt_orderlist_parcel.isEnabled = (checkedsum > 0)
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        getDatas(2)
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        getDatas(1)
    }

    override fun initEvent() {

        val onItemClickListener = OnItemClickListener { adapter, view, position ->
            val item = view.tag as OrderDetailModel
            val menuBean = adapter.getItem(position) as MenuBean
            when (menuBean.name) {
                "watch_refund_detail" -> {//查看退款
                    watchRefundDetail(item.sn)
                }
                "cancel_refund_detail" -> {//取消退款
                    CancelSureViewModel(mActivity).apply {
                        leftStringRes = R.string.确定
                        rightStringRes = R.string.取消
                        contentStringRes = R.string.确认取消申请退款吗
                        leftClick = {
                            mViewModel.cancelRefund(item.sn)
                        }
                    }.show()

                }
                "allow_rog" -> {//确认收货
                    CancelSureViewModel(mActivity, R.string.请收到货后再确认收货) {
                        mViewModel.rog(item.sn)
                    }.show()


                }
                "allow_pay" -> {//去付款
                    if (type == OrderListType.PAY_DIFF) {
                        push(ActCons.DiffOrderActivity, {
                            it.withInt("id", item.order_id)
                        })
                    } else {
                        Asia5bPayUtils.getAuthorization(mActivity as SimpleActivity<*, *>, true) { isCanSkip ->
                            if (isCanSkip) {
                                mViewModel.getTradeSerialNo(item)

                            }
                        }

                    }
                }
                "allow_comment" -> {//评价晒单
                    push(ActCons.PostCommentActivity, {
                        it.withSerializable("data", item)
                    })
                }
                "common_again" -> {//追加评论
                    push(ActCons.CommentAgainActivity, {
                        it.withSerializable("order_sn", item.sn)
                    })
                }
                "check_logis" -> {//查看物流

                    LogisDF().apply {
                        this.orderDetailModel = item
                    }.show(childFragmentManager, "LogisDF")
                }
                "allow_apply_service" -> {//申请售后
//                    push(ActCons.OrderAfterSaleActivity, {
//                        it.withString("orderSn", item.sn)
//                    })
                    push(ActCons.OrderDetail2Activity, {
                        it.withString("orderSn", item.sn)
                    })

                }
                "cancel_order" -> {//取消订单
                    if (TextUtils.equals(item.pay_status, "PAY_YES")) {
                        push(ActCons.OrderAfterSaleActivity, {
                            it.withString("orderSn", item.sn)
                        })
                    } else {
                        var dialog = OrderCancelDialog(mActivity)
                        dialog.show()
                        dialog.setSureClick<String> { reson ->
                            mViewModel.cancel(item.sn, reson)
                        }
                    }
                }
            }

        }
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val item = mAdapter.getItem(position) as OrderDetailModel
            itemClick(item)
        }
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (adapter is OrderDetailmAdapter) {//各种按键
                onItemClickListener.onItemClick(adapter, view, position)
            } else {
                when (view.id) {
                    R.id.rv_orderlist_parcel -> {//子复选框
//                        val parcelModel = adapter.getItem(position) as ParcelModel
                        notifyAllChecked()
                    }
                    R.id.iv_orderlist_check -> {//复选框
                        val orderDetailModel = adapter.getItem(position) as OrderDetailModel
                        orderDetailModel.sent_parcel?.forEach {
                            if (it.isCanParcel) {
                                it.checked = !it.checked
                            }
                        }
                        adapter.notifyItemChanged(position)
                        notifyAllChecked()
                    }
                    R.id.view_orderlist_goods_click -> {
                        val orderDetailModel = adapter.getItem(position) as OrderDetailModel
                        itemClick(orderDetailModel)
                    }
                }
            }
        }
    }

    /**
     * 点击item
     */
    fun itemClick(item: OrderDetailModel) {
        if (type == OrderListType.WAIT_REFUND) {
            watchRefundDetail(item.sn)
        } else if (type != OrderListType.PAY_DIFF) {
            push(ActCons.OrderDetail2Activity, {
                it.withString("orderSn", item.sn)
            })
        }
    }

    fun watchRefundDetail(refundSn: String) {
        push(ActCons.AftersaleDetailActivity, {
            it.withString("sn", refundSn)
        })
    }

    override fun startObserver() {
        mViewModel.getTradeSerialNoResultLiveData.observe(this, Observer {
            getTradeSerialNoResult(it[0]!! as String, it[1] as OrderDetailModel)
        })
        mViewModel.getDatasResultLiveData.observe(this, Observer {
            getDatasResult(it as ResultModel<ArrayList<OrderDetailModel>>)
        })
        mViewModel.rogResultLiveData.observe(this, Observer {
            rogResult()
        })
        mViewModel.cancalResultLiveData.observe(this, Observer {
            cancalResult()
        })

        mViewModel.cancelRefundResultLiveData.observe(this, Observer {
            cancelRefundResult(it)
        })

    }

    override fun lazyFetchData() {
        getDatas(0)
        //提交注释


    }


    fun getDatas(refresh: Int) {
        var houseId: Int? = null
        if (type == OrderListType.APPLY_PACKAGING) {
            houseId = orderListActivity.getCurrentHouseId()
        }
        mViewModel.getDatas(refresh, type, houseId, goods_name)
    }

    fun getDatasResult(resultModel: ResultModel<ArrayList<OrderDetailModel>>) {
        if (resultModel.page <= 1) {
            mDatas.clear()
        }
        if (!resultModel.data.isNullOrEmpty()) {
            mAdapter.addData(resultModel.data!!)
        }
        if (emptyView.parent == null) {
            mAdapter.setEmptyView(emptyView)
        }
        mDataBinding.autoOrderlist.setEnableLoadMore(resultModel.page < resultModel.sumPage)

        if (parentFragment != null && parentFragment is SearchOrderDF) {
            val searchOrderDF = requireParentFragment() as SearchOrderDF
            searchOrderDF.getDatasResult()
        }
    }

    fun rogResult() {
        if (type == orderListActivity.getCurrentType()) {
            getDatas(1)
        }
        orderListActivity.refreshOtherFragmentData()
    }

    fun cancalResult() {
        if (type == orderListActivity.getCurrentType()) {
            getDatas(1)
        }
        orderListActivity.refreshOtherFragmentData()
    }

    var waitOrderPayModel: OrderPayModel? = null
    fun getTradeSerialNoResult(tradeSerialNo: String?, item: OrderDetailModel) {
        waitOrderPayModel = OrderPayModel()
        waitOrderPayModel!!.run {
            tradeType = TradeType.Order
            sn = "${tradeSerialNo}"
            orderSn = item.sn
            payPrice = item.order_price
            Asia5bPayUtils.skipPay(mActivity, this)
        }
    }

    /**
     * 取消售后
     */
    fun cancelRefundResult(orderSn: String) {
        for (model in mDatas) {
            if (TextUtils.equals(model.sn, orderSn)) {
                mDatas.remove(model)
                break
            }
        }
        mAdapter.notifyDataSetChanged()
        orderListActivity.refreshOtherFragmentData()
    }

    override val isRegisterEventBus: Boolean
        get() = true

    //订单打包
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onOrderParcelEvent(event: OrderParcelEvent) {
        if (type == orderListActivity.getCurrentType()) {
            getDatas(1)
        }
        orderListActivity.refreshOtherFragmentData()
    }

    //订单打包
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onCreateOrderEvent(event: CreateOrderEvent) {
        if (type == orderListActivity.getCurrentType()) {
            getDatas(1)
        }
        orderListActivity.refreshOtherFragmentData()
    }

    //订单支付
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onPayEvent(event: PayEvent) {
        if (type == orderListActivity.getCurrentType()) {
            getDatas(1)
        }
        orderListActivity.refreshOtherFragmentData()
    }

    //订单支付
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onPostCommentEvent(event: PostCommentEvent) {
        if (type == orderListActivity.getCurrentType()) {
            getDatas(1)
        }
        orderListActivity.refreshOtherFragmentData()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun paySuccessEvent(tradeSerialNo: String?) {
        waitOrderPayModel?.let {
            if (TextUtils.equals(it.sn, tradeSerialNo)) {
                Asia5bPayUtils.checkOrderPayState(it.orderSn) {
                    if (it) {
                        if (type == orderListActivity.getCurrentType()) {
                            getDatas(1)
                        }
                    }
                }.joinComposite(mCompositeDisposable)
            }
        }
        orderListActivity.refreshOtherFragmentData()
    }


    /**
     *
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAsiaPayEvent(asiaPayEvent: AsiaPayEvent) {
        for (orderDetailModel in mDatas) {
            if (TextUtils.equals(orderDetailModel.sn, asiaPayEvent.orderSn)) {
                mDatas.remove(orderDetailModel)
                mAdapter.notifyDataSetChanged()
                break
            }
        }
        orderListActivity.refreshOtherFragmentData()
    }

    /**
     * 订单取消售后
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onOrderRefundEvent(event: OrderRefundEvent) {
        if (event != null) {
            cancelRefundResult(event.orderSn)
        }
    }

    /**
     * 申请售后,退货退款事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onOrderAfterSaleEvent(event: OrderAfterSaleEvent) {
        if (type == orderListActivity.getCurrentType()) {
            getDatas(1)
        }
        orderListActivity.refreshOtherFragmentData()
    }

}